/*
 * Really easy field validation with Prototype
 * http://tetlaw.id.au/view/javascript/really-easy-field-validation
 * Andrew Tetlaw
 * Version 1.5.4.1 (2007-01-05)
 *
 * Copyright (c) 2007 Andrew Tetlaw
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

if (Validation) {
    Validation.addAllThese([
        ['validate-length-customer-register', 'The maximal length for this field is 35 characters.', function (v, elm) {
            var reMax = new RegExp(/^maximum-length-[0-9]+$/);
            var reMin = new RegExp(/^minimum-length-[0-9]+$/);
            var result = true;
            var length;
            $w(elm.className).each(function (name, index) {
                if (name.match(reMax) && result) {
                    length = name.split('-')[2];
                    result = (v.length <= length);
                }
                if (name.match(reMin) && result && !Validation.get('IsEmpty').test(v)) {
                    length = name.split('-')[2];
                    result = (v.length >= length);
                }
            });
            return result;
        }],
        ['validate-order-period', 'Please enter orderlist period less than 365 in this field.', function (v) {
            if (v.length)
                return parseFloat(v) < 365;
            else
                return true;
        }],
    ]);
}

//Check if the current store has password validation. if not, insert one for default.
if (Validation) {
    if (typeof(Validation.methods['validate-password-' + MAGE_LOCALE_CODE]) == 'undefined' || Validation.methods['validate-password-' + MAGE_LOCALE_CODE] === null) {
        Validation.addAllThese([
            ['validate-password-' + MAGE_LOCALE_CODE, 'Please enter 8 or more characters with at least one number and an uppercase letter. Leading or trailing spaces will be ignored.', function (v) {
                var pass = v.strip();
                var number = new RegExp("[0-9]+");
                var upperCase = new RegExp("[A-Z]+");

                if(!(number.test(v) && upperCase.test(v)) && pass.length > 0) {
                    return false;
                }
                /*strip leading and trailing spaces*/
                return !(pass.length > 0 && pass.length < 8);
            }]
        ]);
    }
}

//jQuery
if (Validation) {
    Validation.addStaticMessage = function (messages, exceptUrls, ignoreElements) {
        var createMessage = function (message, forEle) {
            var id = 'advice-' + message.className + '-' + forEle.attr('id');
            var wrapper = jQuery('<p>', {
                'class': 'validate-static-message form-help',
                'id': id
            });
            wrapper.html(Translator.translate(message.error));
            return wrapper;
        };
        var isExceptionUrl = function () {
            var pathName = location.pathname;
            if (typeof(exceptUrls) != "undefined" && exceptUrls !== null) {
                var i;
                for (i = 0; i < exceptUrls.length; i++) {
                    if (pathName.indexOf(exceptUrls[i]) >= 0) {
                        return true;
                    }
                }
            }
            return false;
        };

        var isIgnoreElements = function (ele) {
            if (typeof(ignoreElements) != "undefined" && ignoreElements !== null) {
                var i;
                for (i = 0; i < ignoreElements.length; i++) {
                    if (ignoreElements[i][0] == ele[0]) {
                        return true;
                    }
                }
            }
            return false;
        };


        jQuery.each(messages, function (index, value) {
            var eles = jQuery(index);
            jQuery.each(eles, function (i, v) {
                var current = jQuery(v);
                if (!isExceptionUrl() || !isIgnoreElements(current)) {
                    var newMessage = createMessage(value, current);
                    newMessage.insertAfter(current);
                }
            });
        });
    };


    //prototype
    Object.extend(Validation, {
        test: function (name, elm, useTitle) {
            var v = Validation.get(name);
            var prop = '__advice' + name.camelize();
            var container;
            var advice;
            try {
                if (Validation.isVisible(elm) && !v.test($F(elm), elm)) {
                    //if(!elm[prop]) {
                    advice = Validation.getAdvice(name, elm);
                    if (advice === null) {
                        advice = this.createAdvice(name, elm, useTitle);
                    }
                    advice.attributes['class'].value = 'validation-advice';
                    this.showAdvice(elm, advice, name);
                    this.updateCallback(elm, 'failed');
                    //}
                    elm[prop] = 1;
                    if (!elm.advaiceContainer) {
                        elm.removeClassName('validation-passed');
                        elm.addClassName('validation-failed');
                    }

                    if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName !== '') {
                        container = elm.up(Validation.defaultOptions.containerClassName);
                        if (container && this.allowContainerClassName(elm)) {
                            container.removeClassName('validation-passed');
                            container.addClassName('validation-error');
                        }
                    }

                    /* IE 8 does not support calling custom events */
                    if (document.createEvent) {
                        fireEvent(elm, 'validationDone');
                    }

                    return false;
                } else {
                    advice = Validation.getAdvice(name, elm);
                    this.hideAdvice(elm, advice);
                    this.updateCallback(elm, 'passed');
                    elm[prop] = '';
                    elm.removeClassName('validation-failed');
                    elm.addClassName('validation-passed');
                    if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName !== '') {
                        container = elm.up(Validation.defaultOptions.containerClassName);
                        if (container && !container.down('.validation-failed') && this.allowContainerClassName(elm)) {
                            if (!Validation.get('IsEmpty').test(elm.value) || !this.isVisible(elm)) {
                                container.addClassName('validation-passed');
                            } else {
                                container.removeClassName('validation-passed');
                            }
                            container.removeClassName('validation-error');
                        }
                    }

                    /* IE 8 does not support calling custom events */
                    if (document.createEvent) {
                        fireEvent(elm, 'validationDone');
                    }

                    return true;
                }
            } catch (e) {
                throw(e);
            }
        },
        showAdvice: function (elm, advice, adviceName) {
            if (!elm.advices) {
                elm.advices = new Hash();
            }
            else {
                elm.advices.each(function (pair) {
                    if (!advice || pair.value.id != advice.id) {
                        // hide non-current advice after delay
                        this.hideAdvice(elm, pair.value);
                    }
                }.bind(this));
            }
            elm.advices.set(adviceName, advice);
            if (typeof Effect == 'undefined') {
                advice.style.display = 'block';
            } else {
                if (!advice._adviceAbsolutize) {
                    new Effect.Appear(advice, {duration: 0.5});
                } else {
                    Position.absolutize(advice);
                    advice.show();
                    advice.setStyle({
                        'top': advice._adviceTop,
                        'left': advice._adviceLeft,
                        'width': advice._adviceWidth,
                        'z-index': 1000
                    });
                    advice.addClassName('advice-absolute');
                }
            }
        },
        hideAdvice: function (elm, advice) {
            if (advice !== null) {
                new Effect.Fade(advice, {
                    duration: 0.5, afterFinishInternal: function () {
                        advice.hide();
                    }
                });
            }
        }
    });
}